package com.gws.ievent.service;

import com.gws.ievent.config.ISchedulerConfig;
import com.gws.ievent.db.model.EventModel;
import com.gws.ievent.db.service.EventLogService;
import com.gws.ievent.db.service.EventService;
import com.gws.ievent.scheduler.SchedulerConfig;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author song
 * @date 2022/10/22 21:56
 */
//@Component
public class StartEventService implements ApplicationListener<ApplicationStartedEvent> {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        // 配置
        ISchedulerConfig config = event.getApplicationContext().getBean(ISchedulerConfig.class);
        this.setConfig(config);

        EventService eventService = event.getApplicationContext().getBean(EventService.class);

        // 从数据库里拿事件
        List<EventModel> models = eventService.getNotDeletedList();
        if (CollectionUtils.isEmpty(models)) {
            return;
        }

        for (EventModel model : models) {
            try {
                // 添加事件到调度器
                EventManageService.add(model);
            } catch (Exception e) {
                // 增加失败日志
                event.getApplicationContext().getBean(EventLogService.class)
                        .create(model.getId(), false, e.getMessage());
            }
        }
    }


    /**
     * 设置配置
     *
     * @param config
     */
    private void setConfig(ISchedulerConfig config) {
        SchedulerConfig schedulerConfig = SchedulerConfig.getInstance();
        schedulerConfig.setWheelTimerThreadFactoryName(config.getWheelTimerThreadFactoryName());
        schedulerConfig.setTickDuration(config.getTickDuration());
        schedulerConfig.setTicksPerWheel(config.getTicksPerWheel());
        schedulerConfig.setThreadPoolThreadName(config.getThreadPoolThreadName());
        schedulerConfig.setCorePoolSize(config.getCorePoolSize());
        schedulerConfig.setMaximumPoolSize(config.getMaximumPoolSize());
        schedulerConfig.setKeepAliveTime(config.getKeepAliveTime());
        schedulerConfig.setMapCapacity(config.getMapCapacity());
    }

}
